package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controllers.SalonController;

/**
 * Servlet implementation class CrearPedidoServlet
 */
public class CrearPedidoServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.getWriter().append("DOGET");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String platosCant = request.getParameter("platos-cant");
		int mesa = Integer.parseInt(request.getParameter("mesa"));

		if (platosCant != null)
		{
			String delim = ",";
			String[] tokens = platosCant.split(delim);
			int start = 0;
			int end = 0;
			boolean success = true;

			for (int i = 0; i < tokens.length && success; i++)
			{
				start = tokens[i].indexOf("{") + 1;
				end = tokens[i].indexOf(":");
				int plato = Integer.parseInt(tokens[i].substring(start, end));
				int cantidad = Integer
						.parseInt(tokens[i].substring(end + 1, tokens[i].indexOf("}")));

				success = SalonController.agregarItemCarta(mesa, plato, cantidad);
			}

			if (success)
			{
				SalonController.confirmarPedido(mesa);
			}
			else
			{
				System.out.println("se produjo un error");
			}
		}

	}

}
